package com.hk.yajin.manager;

import android.os.Handler;
import android.os.Message;

/**
 * 类描述：更新验证码UI
 * 创建人：ham
 * Date：2016/5/24
 * Time: 8:55
 */
public class ObtainValidateCode {
    public boolean hadSendCode=false;
    //获取验证码超时
    public static final int HANDLER_VALIDATE_BUTTON_OF_INIT = 0x1fffffff;
    //获取验证码60秒倒计时
    public static final int HANDLER_UPDATE_VALIDATE_BUTTON = 0x2fffffff;
    private Handler handler;

    public ObtainValidateCode(Handler handler) {
        this.handler = handler;
    }

    public void changeButtonUIAndGetCode(int s) {
        hadSendCode=true;
        final boolean[] validateTag = {true};
        final int[] second = {s + 1};
        Thread thread = new Thread() {
            @Override
            public void run() {
                if (validateTag[0]) {
                    updateValidateCodeView();
                }
                //获取验证码超时,更新UI
                Message message = new Message();
                message.what = HANDLER_VALIDATE_BUTTON_OF_INIT;
                handler.sendMessage(message);
            }

            private void updateValidateCodeView() {
                while (second[0] > 1) {
                    try {
                        second[0]--;
                        //获取验证码60秒倒计时，更新UI
                        Message message = new Message();
                        message.what = HANDLER_UPDATE_VALIDATE_BUTTON;
                        message.obj = second[0];
                        handler.sendMessage(message);
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                validateTag[0] = false;
            }
        };
        thread.start();
    }
}
